package com.hup.utils.commons.start;

import com.hup.utils.commons.exception.AppExceptionHandler;
import lombok.Getter;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;

/**
 * @author hugan
 * @date 2020/4/10
 */
public class AppIcon {

    /*
    @Bean
    public AppIcon appIcon() {
        return new AppIcon("/img/app_tray.gif");
    }
    */

    @Getter
    private final ImageIcon appIcon;

    /**
     * @param imgPath jar内部的图标
     */
    public AppIcon(String imgPath) {
        appIcon = getIcon(imgPath, "程序图标");
    }

    public Image getImage() {
        return appIcon.getImage();
    }

    /**
     * @param imgPath 如:[/img/cursor.gif]
     * @return notNull,加载异常时会有确认弹窗并返回[橙色问号图标]
     * @apiNote 支持jar和war,不支持外部文件
     */
    public static ImageIcon getIcon(String imgPath, String desc) {
        URL url = BaseAppTray.class.getResource(imgPath);
        if (url != null) {
            ImageIcon res = new ImageIcon(url);
            if (res.getIconWidth() != -1 && res.getIconHeight() != -1) {
                return res;
            }
        }

        String msg = "[" + desc + "]加载异常:[" + imgPath + "]";
        AppExceptionHandler.handle(new Throwable(msg));
        DialogHelper.confirm(msg).warn().onTop(true).show();

        //绘制[问号图标]
        int wid = 200;
        BufferedImage image = new BufferedImage(wid, wid, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);//看得出效果
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);//看不出效果

        g.setColor(Color.ORANGE);
        g.fillOval(0, 0, wid, wid);
        g.setColor(Color.WHITE);
        g.setFont(new Font("黑体", Font.BOLD, wid));
        g.drawString("?", wid / 4, wid / 5 * 4);
        g.dispose();
        return new ImageIcon(image);
    }

}
